package com.scc.persistence;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public class GenericDAO<T>
{
   public Class<T> persistentClass;
   
   public T getByCode(String code, Session session)
   {
      Criteria crit = session.createCriteria(persistentClass);
      crit.add(Restrictions.eq("code", code));
      
      @SuppressWarnings("unchecked")
      List<T> list = crit.list();
      return list.size() == 0 ? null : list.get(0);
   }
   
   @SuppressWarnings("unchecked")
   public T getFirst(Session  session)
   {
      Criteria crit = session.createCriteria(persistentClass);
      crit.addOrder(Order.asc("code"));
      
      List<T> list = crit.list();
      return list.size() == 0 ? null : list.get(0);
   }
   
   @SuppressWarnings("unchecked")
   public List<T> getAll(Session session)
   {
      Criteria crit = session.createCriteria(persistentClass);
      List<T> result = crit.list();
      return result;
   }
   
   @SuppressWarnings("unchecked")
   public GenericDAO()
   {
      this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
            .getActualTypeArguments()[0];
   }
         
}
